package lol.oxguy3.android.mcmc;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewGroup;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ServerListActivity extends Activity implements OnItemClickListener {

	public final String SERVERS_FILENAME = "servers.txt";
	public final String PARAM_SEP = "\u00A4"; /**the character that separates the properties of a server in the storage file*/
	
	Context cxt;
	ListView slListView;
	SharedPreferences settings;
	ArrayList<MinecraftServer> serverAl;
	ArrayAdapter<MinecraftServer> slAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.serverlist);
		cxt = this;
        
        Bundle errmsgbundle = getIntent().getExtras();
        if (errmsgbundle != null && errmsgbundle.containsKey("errormessage")) {
        	Toast.makeText(cxt, errmsgbundle.getString("errormessage"), Toast.LENGTH_SHORT).show();
        }
        
        
        settings = PreferenceManager.getDefaultSharedPreferences(this);
		

        slListView = (ListView) findViewById(R.id.listViewServers);
        
		ArrayList<String> textOfServers = loadServerList(false);
		serverAl = new ArrayList<MinecraftServer>();
		
		slAdapter = new ArrayAdapter<MinecraftServer>(cxt, R.id.listViewServers, serverAl){
			@Override
			public View getView (int position, View convertView, ViewGroup parent) {
				TextView view = new TextView(cxt);
				//view.setTextColor(0);
		        view.setHeight(30);
				view.setText(getItem(position).getName());
				return view;
			}
		};
		slListView.setAdapter(slAdapter);
		slListView.setOnItemClickListener(this);
		
		for (int i = 0; i < textOfServers.size(); i++) {
			String rawServerData = textOfServers.get(i);
			String[] serverDataArr = rawServerData.split(PARAM_SEP);
			//System.out.println(serverDataArr[2] + " ~ " + serverDataArr[0] + " ~ " + serverDataArr[1]);
			slAdapter.add(new MinecraftServer(serverDataArr[2], serverDataArr[0], Integer.parseInt(serverDataArr[1])));
			//serverAl.add(new MinecraftServer(serverDataArr[2], serverDataArr[0], Integer.parseInt(serverDataArr[1])));
		}
		
	}
	
	
	/**
	 * Loads the server list from a file. If a FileNotFoundException or an IOException occur,
	 * it will run generateNewServerList() and then call back to itself (the parameter isRetry
	 * is set to true in these callbacks to stop an infinite loop from happening)
	 * 
	 * @param isRetry should be false when not used inside the function
	 * @return an ArrayList that contains all the servers as raw Strings
	 */
	public ArrayList<String> loadServerList(boolean isRetry) {
		
		ArrayList<String> returnList = new ArrayList<String>();
		try {
			InputStream in = openFileInput(SERVERS_FILENAME);
			if (in!=null) {
				BufferedReader bro = new BufferedReader(new InputStreamReader(in));
				String line;
				while ((line=bro.readLine())!=null) {
					returnList.add(line);
				}
			}
			
		} catch (FileNotFoundException e) { //TODO this *will* happen the first time the user ever starts the app; need to fix that elegantly
			if (!isRetry) {
				Toast.makeText(this, "Server list missing, generating a new one...", Toast.LENGTH_SHORT).show();
				generateNewServerList();
				return loadServerList(true);
			} else {
				Toast.makeText(this, "Server list still unavailable. All hope is lost. Killing self...", Toast.LENGTH_SHORT).show();
				System.exit(1);
			}

		} catch (IOException e) {
			if (!isRetry) {
				Toast.makeText(this, "Server list could not be accessed, attempting to generate a new one...", Toast.LENGTH_SHORT).show();
				generateNewServerList();
				return loadServerList(true);
			} else {
				Toast.makeText(this, "Server list still unavailable. All hope is lost. Killing self...", Toast.LENGTH_SHORT).show();
				System.exit(1);
			}
			
		}
		return returnList;
	}
	
	
	
	public void generateNewServerList() {
		FileOutputStream fos;
        String sampleServers = "192.168.1.123" + PARAM_SEP + "25565" + PARAM_SEP + "Server 1" + "\n" + "mc.example.com" + PARAM_SEP + "25565" + PARAM_SEP + "Server 2"+ "\n" + "18.187.1.88" + PARAM_SEP + "25565" + PARAM_SEP + "David Hasselhoff's Van of Dreams";
		try {
			fos = openFileOutput(SERVERS_FILENAME, Context.MODE_PRIVATE);
			fos.write(sampleServers.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Toast.makeText(cxt, "A file not found error occurred while generating new server list: " + e.getMessage(), Toast.LENGTH_SHORT).show();
			
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(cxt, "A read/write error occurred while generating new server list: " + e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}
	
	
    @Override
    public boolean onCreateOptionsMenu(Menu m) {
    	MenuInflater pump = getMenuInflater();
    	pump.inflate(R.menu.menu_sl, m);
    	
		return true;
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem mi) {
    	if (mi.getItemId() == R.id.item_sl_addServer) {
    		Toast.makeText(cxt, "Not yet implemented!", Toast.LENGTH_SHORT).show(); //TODO make EditServerActivity.java!
    		return true;
    		
    	} else if (mi.getItemId() == R.id.item_sl_settings) {
			Intent settingsIntent = new Intent(this, SettingsActivity.class);
	        startActivity(settingsIntent);
    		return true;
    		
    	} else {
    		
    		return super.onOptionsItemSelected(mi);
    	}
    	
    }


	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		//if (view.equals(slListView)) {

	        Intent intentChat = new Intent(cxt, ServerChatActivity.class);
	        intentChat.putExtra("address", ((MinecraftServer)slAdapter.getItem(position)).getAddress());
	        intentChat.putExtra("port", ((MinecraftServer)slAdapter.getItem(position)).getPort());
	        cxt.startActivity(intentChat);
			
		/*} else {
			Toast.makeText(cxt, "You clicked an item in a ListView that doesn't exist, you sneaky bastard.", Toast.LENGTH_SHORT).show();
		}*/
	}
}
